package com.shuaixin.web.controller;

import javax.servlet.http.HttpServletRequest;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shuaixin.web.rebackmodel.RegisterBack;
import com.shuaixin.web.rebackmodel.UploadBack;
import com.shuaixin.web.rebackmodel.UserInfoBack;
import com.shuaixin.web.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;


import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.shuaixin.web.model.User;
import com.shuaixin.web.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceI UserManagerImpl;

    @RequestMapping(value = "/uploadUserAvatar", method = RequestMethod.POST)
    @ResponseBody
    public UploadBack uploadUserAvatar(@RequestParam(value = "uuid") String uuid,
                                       HttpServletRequest request) throws Exception {
        UploadBack uploadBack = new UploadBack();

        if (uuid != "" || uuid != null) {
            User user = UserManagerImpl.getUserByuuid(uuid);
            if (user == null) {
                uploadBack.setErrcode(ErrorCodeUtils.EC_UNKNOWN);
                uploadBack.setSuccess(false);
                uploadBack.setUser(null);
            } else {
                MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
                CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
                if (!cfile.isEmpty()) {
                    byte[] bfile = cfile.getBytes();
                    String fileName = "";

                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    fileName = format.format(new Date());

                    Random random = new Random();
                    for (int i = 0; i < 3; i++) {
                        fileName = fileName + random.nextInt(9);
                    }

                    String origFileName = cfile.getOriginalFilename();

                    //XXX.jpg
                    String suffix = origFileName.substring(origFileName.lastIndexOf("."));
                    String path = request.getSession().getServletContext().getRealPath("");
                    String avatarurl = "/assets/img/" + fileName + suffix;
                    OutputStream out = new FileOutputStream(new File(path + "/assets/img/" + fileName + suffix));
                    out.write(bfile);
                    out.flush();
                    out.close();
                    uploadBack.setAvatarUrl(avatarurl);
                    uploadBack.setErrcode(0);
                    uploadBack.setSuccess(true);
                    user.setAvatarurl(avatarurl);
                    uploadBack.setUser(user);
                    UserManagerImpl.updateUser(user);
                }
            }
            return uploadBack;
        } else {
            uploadBack.setErrcode(ErrorCodeUtils.EC_UNKNOWN);
            uploadBack.setSuccess(false);
            uploadBack.setUser(null);
            return uploadBack;
        }
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public RegisterBack addUser(@RequestParam(value = "name") String name,
                                @RequestParam(value = "age", defaultValue = "0") int age,
                                @RequestParam(value = "sex", defaultValue = "男") String sex,
                                @RequestParam(value = "email", defaultValue = "") String email,
                                @RequestParam(value = "phoneNumber", defaultValue = "") String phoneNumber,
                                @RequestParam(value = "passwd") String passwd,
                                HttpServletRequest request) {

//
        User user = new User();
        RegisterBack registerBack = new RegisterBack();
        if (email == null || email.length() <= 0) {
            registerBack.setErrcode(ErrorCodeUtils.EC_PARAMETERS_OUTOFBOUND);
            return registerBack;
        }
        if (!RegexValidator.isEmail(email)) {
            registerBack.setErrcode(ErrorCodeUtils.EC_ERROR_WRONG_PARAM_FORMAT);
            return registerBack;
        }

        User userFound = UserManagerImpl.getUserByEmail(email);
        if (userFound != null) {
            registerBack.setErrcode(ErrorCodeUtils.EC_PARAMETERS_OUTOFBOUND);
            return registerBack;
        }


        UUID uuid = UUID.randomUUID();
        user.setUuid(uuid.toString());
        user.setName(name);
        user.setAge(age);
        user.setSex(sex);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setPasswd(passwd);
        user.setSigntext("");
        user.setAvatarurl("");
        user.setAddress("");
        System.out.println("user=" + user.toString());
        String id = UserManagerImpl.addUser(user);
        if (id.length() <= 0) {
            registerBack.setErrcode(ErrorCodeUtils.EC_UNKNOWN);
        } else {
            registerBack.setErrcode(ErrorCodeUtils.EC_SUCCESS);
            registerBack.setSuccess(true);
            registerBack.setUuid(uuid.toString());
        }
        return registerBack;
    }

    @RequestMapping("/login")
    @ResponseBody
    public UserInfoBack userLogin(@RequestParam(value = "email") String email,
                                  @RequestParam(value = "passwd") String passwd
    ) {
        UserInfoBack userInfoBack = new UserInfoBack();
        if (email == null || email.length() <= 0) {
            userInfoBack.setErrcode(ErrorCodeUtils.EC_PARAMETERS_OUTOFBOUND);
            return userInfoBack;
        }
        if (!RegexValidator.isEmail(email)) {
            userInfoBack.setErrcode(ErrorCodeUtils.EC_ERROR_WRONG_PARAM_FORMAT);
            return userInfoBack;
        }

        User userFound = UserManagerImpl.getUserByEmai_Passwdl(email, passwd);
        if (userFound == null) {
            userInfoBack.setErrcode(ErrorCodeUtils.EC_UNKNOWN);
            return userInfoBack;
        }
        if (userFound.getPasswd().equals(passwd)) {
            userInfoBack.setSuccess(true);
            userInfoBack.setErrcode(ErrorCodeUtils.EC_SUCCESS);
            userInfoBack.setUser(userFound);
            SMTPSender smtpSender = new SMTPSender(email, "welcome", "登录成功");
            smtpSender.putEmail();
        } else {
            userInfoBack.setErrcode(ErrorCodeUtils.ERROR_WRONG_EMAIL_PWD);
        }
        return userInfoBack;
    }


    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public UserInfoBack updateUser(@RequestParam(value = "userJson") String userJson) {
        UserInfoBack userInfoBack = new UserInfoBack();
        JSONObject obj =  JSON.parseObject(userJson);
        User user = UserManagerImpl.getUserByuuid(obj.getString("uuid"));
        if(user !=null){
            user.setName(obj.getString("name"));
            user.setAge(Integer.parseInt(obj.getString("age")));
            user.setSex(obj.getString("sex"));
            user.setEmail(obj.getString("email"));
            user.setPasswd(obj.getString("passwd"));
            user.setAddress(obj.getString("address"));
            user.setSigntext(obj.getString("signtext"));
            user.setPhoneNumber(obj.getString("phoneNumber"));
            User userback = UserManagerImpl.updateUser(user);
            if (userback != null) {
                userInfoBack.setUser(userback);
                userInfoBack.setSuccess(true);
                userInfoBack.setErrcode(0);
                return userInfoBack;
            } else {
                userInfoBack.setUser(null);
                userInfoBack.setSuccess(false);
                userInfoBack.setErrcode(-1);
                return userInfoBack;
            }
        }
        userInfoBack.setUser(null);
        userInfoBack.setSuccess(false);
        userInfoBack.setErrcode(-1);
        return userInfoBack;

    }


    @RequestMapping("/getUserInfo")
    @ResponseBody
    public UserInfoBack getUserInfo(@RequestParam(value = "uuid") String uuid) {
        UserInfoBack userInfoBack = new UserInfoBack();

        User user = UserManagerImpl.getUserByuuid(uuid);
        if (user == null) {
            userInfoBack.setErrcode(ErrorCodeUtils.EC_UNKNOWN);
            userInfoBack.setSuccess(false);
            userInfoBack.setUser(null);
        } else {
            userInfoBack.setUser(user);
            userInfoBack.setErrcode(0);
            userInfoBack.setSuccess(true);
        }


        return userInfoBack;
    }
}
